//
//  LVView.swift
//  SwiftLua
//
//  Created by xiaerfei on 2019/7/26.
//  Copyright © 2019 xiaerfei. All rights reserved.
//

import UIKit
import Lua

class LVView: UIView {
    let luaVM = Lua.VirtualMachine()
    var globleClass: Dictionary<Int64, UIView> = [:]

    convenience init() {
        self.init()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        registerLib()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    public func runFile(name:String,type:String) {
        
        let path = Bundle.main.path(forResource: name, ofType: type)
        do {
            let content = try String.init(contentsOfFile: path!, encoding: .utf8)
            let _ = self.luaVM.eval(content)
        } catch {
            print("Unexpected non-vending-machine-related error: \(error)")
        }
    }
    
    public func runPackage(package:String) {
        
    }
    
    func registerLib() -> Void {
        let obj = self.luaVM.createTable()
        obj["new"] = self.luaVM.createFunction([String.arg], { args -> SwiftReturnValue in
            let (className) = (args.string)
            if className == "root" {
                let hash = Int64(self.hashValue)
                self.globleClass[hash] = self;
                return .value(hash)
            }
            let cls = NSClassFromString(className)! as! UIView.Type
            let v = cls.init()
            let hash = Int64(v.hashValue)
            self.globleClass[hash] = v;
            print(hash)
            return .value(hash)
        })
        
        obj["addSubView"] = self.luaVM.createFunction([Int64.arg,Int64.arg], { args -> SwiftReturnValue in
            let (selfId,subId) = (args.integer,args.integer)
            let selfView = self.globleClass[selfId]
            let subView = self.globleClass[subId]
            if subView != nil {
                selfView?.addSubview(subView!)
            }
            return .value(0)
        })
        
        obj["insertSuper"] = self.luaVM.createFunction([Int64.arg], { args -> SwiftReturnValue in
            let (viewId) = (args.integer)
            let subView = self.globleClass[viewId]
            if subView != nil {
                self.addSubview(subView!)
            }
            return .value(0)
        })
        
        obj["setValueForKey"] = self.luaVM.createFunction([Table.arg], { args -> SwiftReturnValue in
            let (table) = (args.table)
            let type = (table["type"] as! Number).toInteger()
            let name = table["name"] as! String
            let id = (table["id"] as! Number).toInteger()
            
            
            let view = self.globleClass[id]
            if type == 1 {
                let value = table["value"] as! Table
                let rect = value.toRect()
                if view != nil {
                    view!.setValue(rect, forKey: name)
                }
            } else if type == 2 {
                let colorName = table["value"]  as! String
                let color = UIColor(colorName)
                if view != nil {
                    view!.setValue(color, forKey: name)
                }
            }
            return .value(0)
        })
        self.luaVM.globals["viewobj"] = obj
    }
}
